<template>
  <div>
    <a-form-model layout="inline" ref="formInlineRef" :model="formInline">
      <a-form-model-item label="菜单ID" prop="menuId">
        <a-input allowClear v-model="formInline.menuId"/>
      </a-form-model-item>
      <a-form-model-item label="菜单名" prop="note">
        <a-input allowClear v-model="formInline.note"/>
      </a-form-model-item>
      <a-form-model-item>
        <a-button @click="searchBtn()" type="primary">查询</a-button>
      </a-form-model-item>

      <a-form-model-item>
        <a-button @click="reSearchBtn()">重置</a-button>
      </a-form-model-item>

    </a-form-model>
    <vxe-toolbar>
      <template v-slot:buttons>
<!--        <vxe-button @click="$refs.xTree.toggleTreeExpand(tableData[1])">切换第二行展开</vxe-button>-->
<!--        <vxe-button @click="$refs.xTree.setTreeExpand([tableData[1], tableData[3]], true)">设置第二、四行展开-->
<!--        </vxe-button>-->
        <vxe-button @click="$refs.xTree.setAllTreeExpand(true)">展开所有</vxe-button>
        <vxe-button @click="$refs.xTree.clearTreeExpand()">关闭所有</vxe-button>
        <vxe-button @click="addMenuBtn">新增菜单</vxe-button>
      </template>
    </vxe-toolbar>

    <vxe-table
        border highlight-hover-row
        resizable :auto-resize="true"
        ref="xTree"
        @checkbox-all="selectAllEvent"
        @checkbox-change="selectChangeEvent"
        row-id="menuId" :loading="loading"
        :tree-config="{lazy: true, children: 'children', hasChild: 'hasChild', loadMethod: loadChildrenMethod }"
        :data="tableData">
      <vxe-table-column field="menuId" title="菜单ID" width="120" tree-node></vxe-table-column>
      <vxe-table-column field="note" title="菜单/路由描述" width="150"></vxe-table-column>
      <vxe-table-column field="parentMenuId" title="父菜单ID"></vxe-table-column>
      <vxe-table-column field="menuLevel" title="菜单级别"></vxe-table-column>
      <vxe-table-column field="isMenu" title="是否为菜单">
        <template v-slot="{ row }">
          {{ row.isMenu === 1 ? "是" : "否" }}
        </template>
      </vxe-table-column>
      <vxe-table-column field="iconType" title="图标"></vxe-table-column>
      <vxe-table-column field="hasChild" title="含有子菜单"></vxe-table-column>
      <vxe-table-column field="menuSequence" title="排序号"></vxe-table-column>
      <vxe-table-column field="menuKey" title="菜单Key"></vxe-table-column>
      <vxe-table-column field="routerComponent" title="组件名"></vxe-table-column>
      <vxe-table-column field="routerName" title="路由名"></vxe-table-column>
      <vxe-table-column field="routerPath" title="路由地址"></vxe-table-column>
      <vxe-table-column field="addTime" title="添加时间"></vxe-table-column>
      <vxe-table-column field="updateTime" title="修改时间"></vxe-table-column>
      <vxe-table-column title="操作" width="110" show-overflow>
        <template v-slot="{ row }">
          <!--                    <vxe-button type="text" icon="fa fa-eye"></vxe-button>-->
          <!--                    <vxe-button type="text" icon="fa fa-edit"></vxe-button>-->
          <a-button size="small" type="danger" @click="removeRowEvent(row)">
            <a-icon type="delete"/>
            删除
          </a-button>
          <!--                    <vxe-button type="text" icon="fa fa-trash-o" @click="removeRowEvent(row)"></vxe-button>-->
          <!--                    <vxe-button type="text" icon="fa fa-id-card-o"></vxe-button>-->
        </template>
      </vxe-table-column>
    </vxe-table>


    <AddMenu @refreshTreeTable="reSearchBtn" ref="addMenuRef"></AddMenu>
  </div>
</template>

<script>
import XEUtils from 'xe-utils';
import AddMenu from './menu-child/add-menu';

export default {
  name: "MenuManage",
  components: {
    AddMenu
  },
  data() {
    return {
      selectedRowsData: [],
      loading: false,
      tableData: [],
      formInline: {
        note: '',
        menuId: '',
        parentMenuId: ''
      }

    }
  },
  created() {
    this.formInline.parentMenuId = 0;
    this.findList()
  },
  methods: {
    //新增菜单
    addMenuBtn() {
      this.$refs.addMenuRef.showModal();


    },


    selectAllEvent({checked, records}) {
      console.log(checked ? '所有勾选事件' : '所有取消事件', records);
      this.selectedRowsData = records;
    },
    selectChangeEvent({checked, records}) {
      console.log(checked ? '勾选事件' : '取消事件', records);
      this.selectedRowsData = records;
    },

    searchBtn() {
      this.formInline.parentMenuId = '';
      this.findList();
    },
    reSearchBtn() {
      this.$refs.formInlineRef.resetFields(); //使用前需要在 form-item上加注prop属性
      this.formInline.parentMenuId = 0;
      this.findList();
    },
    removeRowEvent(row) {
      this.$XModal.confirm('您确定要删除吗？').then(type => {
        if (type === 'confirm') {
          console.warn(row)
          const matchObj = XEUtils.findTree(this.tableData, item => item === row, this.treeConfig)
          if (matchObj) {
            // 从树节点中移除
            matchObj.items.splice(matchObj.index, 1);

            let url = '/lte/menu/delMenuByIds?ids=' + row.menuId;
            this.$reqGlobal.delete(url).then(res => {
              console.log(res);
              if (res.data.code === 0) {
                this.$message.success("操作成功!")
              }
            });

          }
        }
      })
    },
    getTreeExpansionEvent() {
      let treeExpandRecords = this.$refs.xTree.getTreeExpandRecords()
      this.$XModal.alert(treeExpandRecords.length)
    },

    findList() {
      this.loading = true;
      let reqJson = {
        parentMenuId: this.formInline.parentMenuId,
        menuId: this.formInline.menuId,
        note: this.formInline.note
      };
      this.$reqGlobal.get('/lte/menu/list', {params: reqJson}).then(resp => {
        this.loading = false;

        console.log(resp)
        let res = [];
        res = resp.data.data;
        // res = JSON.parse(JSON.stringify(resp.data.data));
        res.forEach(r => {
          if (r.hasChild === 1) {
            r.children = [];
            r.hasChild = true;
          } else {
            r.hasChild = false;
          }
        });

        let flg1 = false;
        let flg2 = false;
        res.forEach(k => {
          if (k.menuLevel === 1) {
            flg1 = true;
          }
        });
        res.forEach(t => {
          if (t.menuLevel === 2) {
            flg2 = true;
          }
        });
        //查询结果既有1级又有2级，则只保留1级，2级菜单会在用户触发懒加载时拿到数据
        if (flg1 === true && flg2 === true) {
          let kwt = [];
          res.forEach(t => {
            if (t.menuLevel !== 2) {
              kwt.push(t);
            }
          });
          this.tableData = kwt;
        } else {
          this.tableData = res;
        }
      });
    },


    loadChildrenMethod({row}) {
      this.loading = true;
      // 异步加载子节点
      return new Promise(resolve => {
        setTimeout(() => {
          resolve();

          this.$reqGlobal.get('/lte/menu/list', {params: {parentMenuId: row.menuId}}).then(res => {

            let resB = [];
            resB = res.data.data;
            resB.forEach(b => {
              b.hasChild = false;
            });
            row.children = resB;
            this.loading = false;
            console.log(row);
            console.log(XEUtils.indexOf(this.tableData, row))
            let index = XEUtils.indexOf(this.tableData, row);
            this.$refs.xTree.toggleTreeExpand(this.tableData[index]);
          });
        }, 500);

      });

    }
  }
}
</script>

<style scoped>

</style>